package cn.cmcc.online.smsapi.sdk.db.base;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.JsonUtil;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;

public class BaseManager {
	
	/**
	 * jsonObject 转换成  ContentValues 
	 * 依据列名组从 jsonObject 中取对应的值 填充 ContentValues
	 * 前提条件是需要确保,需要转换的ContentValues 中的字段与 jsonObject中的key要一一对应,
	 * @param values
	 * @param jsonObject
	 * @param cols values的字段与 jsonObject 必须一致
	 * @return values
	 */
	  public static ContentValues getContentValues(ContentValues values,boolean needValue,JSONObject jsonObject,String... cols){
	    	if(jsonObject == null || cols.length == 0)return null;
			if(values == null){
				values = new ContentValues();
			}
			int len = cols.length;
			String temp=null;
		    for(int i = 0; i < len;i++){
		    	temp=(String)JsonUtil.getValueFromJsonObject(jsonObject, cols[i]);
		    	if(needValue && StringUtils.isNull(temp)) continue;
		    	values.put(cols[i],JsonUtil.getValueFromJsonObject(jsonObject, cols[i]).toString());
		    }
			return values;
	    }
	  
		/**
		 * jsonObject 转换成  ContentValues 
		 * 依据列名组从 jsonObject 中取对应的值 填充 ContentValues
		 * 前提条件是需要确保,需要转换的ContentValues 中的字段与 jsonObject中的key要一一对应,
		 * @param values
		 * @param valuesCols
		 * @param objKeys  键值需要成对出现.
		 * @param changeable true时，json没有取到值就不put到values
		 * @return values	
		 */
		  public static ContentValues getContentValues(ContentValues values,String [] valuesCols,String objKeys[],JSONObject jsonObject,boolean changeable){
		    	if(jsonObject == null || valuesCols ==null || objKeys ==null )return null;
		    	int vLen = valuesCols.length;
		    	int oLen = objKeys.length;
		    	if(vLen == 0 || vLen != oLen )return null;
				if(values == null){
					values = new ContentValues();
				}
			    for(int i = 0; i < vLen;i++){
			    	if(changeable){
			    		JsonUtil.putJsonToConV(values, jsonObject, valuesCols[i], objKeys[i]);
			    	}else{
			    		values.put(valuesCols[i],JsonUtil.getValueFromJsonObject(jsonObject, objKeys[i]).toString());
			    	}
			    }
				return values;
		    }
	/**
	 * 获取 ContentValues数据
	 * @param values
	 * @param args  键值需要成对出现
	 * @return
	 */
	  public static ContentValues getContentValues(ContentValues values,String... args){
		 return getContentValues(values,false,args);
	    }
	  /**
	   * 
	   * @param values
	   * @param needValue key,与value必须都有值
	   * @param args key-value对
	   * @return 
	   */
	  public static ContentValues getContentValues(ContentValues values,boolean needValue,String... args){
		  if(args == null || args.length % 2 != 0)return null;
			if(values == null){
				values = new ContentValues();
			}
			int len = args.length;
			for(int i = 0; i < len; i+=2){
				if(needValue && (StringUtils.isNull(args[i]) || StringUtils.isNull(args[i+1]))){
					continue;
				}
				values.put(args[i], StringUtils.getNoNullString(args[i+1]));
			}
			return values;
	  }
	/**
	 * 加载数据,从数据游标中
	 * @param columns 需要加载的数据列
	 * @param cursor 游标
	 * @return 数据集
	 */
	  public static JSONArray loadArrDataFromCursor(String[] columns,XyCursor cursor){
		 if(cursor != null){
	        	try{
	        	JSONObject  tempObj =null;
	        	JSONArray jsonArr = new JSONArray();
	        	while(cursor.moveToNext()){
	        		tempObj = new JSONObject();
	        		for(int i =0; i< columns.length;i++){
	        			tempObj.put(columns[i],StringUtils.getNoNullString(cursor.getString(i)));
	        		}
	        		jsonArr.put(tempObj);
	        	}
	        	
	        	return jsonArr;
	        	}catch(Throwable e){
                /* sdk-593 hewengao/20160819 start */
                LogManager.w("BaseManager", "loadArrDataFromCursor Throwable=", e);
                /* sdk-593 hewengao/20160819 end */
	        	}finally{
// 	        		XyCursor.closeCursor(cursor,true);
	        	}
	        }
	    	return null;
	}
	/**
	 * 加载单个数据
	 * @param columns
	 * @param cursor
	 * @return
	 */
	  public static JSONObject loadSingleDataFromCursor(String[] columns,XyCursor cursor){
		 if(cursor != null){
	        	try{
	        	JSONObject  tempObj =null;
	        	if(cursor.moveToNext()){
	        		tempObj = new JSONObject();
	        		for(int i =0; i< columns.length;i++){
	        			tempObj.put(columns[i],StringUtils.getNoNullString(cursor.getString(i)));
	        		}
	        	}
	        	return tempObj;
	        	}catch(Throwable e){
                    /* sdk-593 hewengao/20160819 start */
                    LogManager.w("BaseManager", "loadSingleDataFromCursor Throwable=", e);
                    /* sdk-593 hewengao/20160819 end */
	        	}finally{
//	        	    XyCursor.closeCursor(cursor, true);
	        	} 
	        }
	    	return null;
	}
	 /**
		 * 加载数据,从数据游标中
		 * @param columns 需要加载的数据列
		 * @param cursor 游标
		 * @return Map<String, JSONObject> 数据集
		 */
	public static Map<String, JSONObject> loadMapDataFromCursor(String[] columns,int keyIndex,XyCursor cursor){
			 if(cursor != null){
		        	try{
		        	JSONObject  tempObj =null;
		        	Map<String, JSONObject> res = new HashMap<String,JSONObject>();
		        	while(cursor.moveToNext()){
		        		tempObj = new JSONObject();
		        		for(int i =0; i< columns.length;i++){
		        			tempObj.put(columns[i],StringUtils.getNoNullString(cursor.getString(i)));
		        		}
		        		res.put((String)JsonUtil.getValueFromJsonObject(tempObj, columns[keyIndex]),tempObj);
		        	}
		        	 return res;
		        	}catch(Throwable e){
                        /* sdk-593 hewengao/20160819 start */
                        LogManager.w("BaseManager", "loadMapDataFromCursor Throwable=", e);
                        /* sdk-593 hewengao/20160819 end */
		        	}finally{
//		        		XyCursor.closeCursor(cursor,true);
		        	}
		        }
		    	return null;
		}
	 
	 /**
		 * 获取单字段的值个数据
		 * @param columns
		 * @param cursor
		 * @return
		 */
		private static String loadSingleFeildDataFromCursor(String columnName,XyCursor cursor){
			 String colValue=null;
			 if(cursor != null){
		        	try{
		        	  if(cursor.moveToNext()){
		        		int index=cursor.getColumnIndex(columnName);
		        		 colValue=cursor.getString(index);
		        	   }
		        	}catch(Throwable e){
                        /* sdk-593 hewengao/20160819 start */
                        LogManager.w("BaseManager", "loadSingleFeildDataFromCursor Throwable=", e);
                        /* sdk-593 hewengao/20160819 end */
		        	}finally{
//		        		cursor.close(true);
		        	}
		        }
		    	return colValue;
		}
		 /**
		  * 保存或更新表记录数据
		  * @param db
		  * @param tableName
		  * @param values
		  * @param where
		  * @param args
		  * @return
		 * @throws Throwable 
		  */
		 public static long saveOrUpdate(SQLiteDatabase db,String tableName,ContentValues values,String where,String args[]) throws Exception{
			 synchronized (DBManager.dblock) {
    		     long flag=-1;
    			 try{
    			 flag = db.update(tableName, values, where,args);
    			 }catch(Throwable e){
    				 throw new Exception();
    			 }
    			 if(flag == 0){
    				 try{
    				  flag=db.insert(tableName,null, values);
    				 }catch(Throwable e){
    					 throw new Exception();
    				 }
    			 }else{
    				 flag = 0;
    			 }
    			 return flag;
			 }
		 }
		 /**
		  * 新增或列新数据
		  * @param TABLE_NAME
		  * @param mainFieldName
		  * @param where
		  * @param whereArgs
		  * @param valueArgs
		  * @return
		  */
			public static long insertOrUpdate(String TABLE_NAME,String mainFieldName,String where,String[] whereArgs,String... valueArgs){
				long result=-1;		
				XyCursor xyCursor=null;
				try {
					String cols []=new String[]{mainFieldName};
					 
					xyCursor=DBManager.query(TABLE_NAME, cols,where,
							whereArgs);
					
					if(xyCursor!=null && xyCursor.getCount() > 0){
						JSONObject obj=BaseManager.loadSingleDataFromCursor(cols, xyCursor);
						result=(Integer)JsonUtil.getValueFromJsonObject(obj, mainFieldName);
		 		
					}else{
		                ContentValues values=BaseManager.getContentValues(null, valueArgs);
						result=DBManager.insert(TABLE_NAME,  values);
						 
					}
				} catch (Throwable e) {			
//					e.printStackTrace();
				    /*SDK-550 hewengao 20160719 start*/
		             LogManager.w(Constant.TAG, "insertOrUpdate: ", e);
		             /*SDK-550 hewengao 20160719 end*/
				}finally{
					 XyCursor.closeCursor(xyCursor, true);
				
				}
				return result;
			}
		 /**
		  * 更新
		  * @param tableName 表名
		  * @param where 条件
		  * @param args  条件参数
		  * @param valueArgs 更新的key-value对
		  * @return rows 修改行数
		  */
		 public static int update(String tableName,String where,String args[],String ... valueArgs){
			int rows = 0;
			try {
				ContentValues values = BaseManager.getContentValues(null, valueArgs);
				rows = DBManager.update(tableName, values,where, args);
			} catch (Throwable e) {
//				e.printStackTrace();
			    /*SDK-550 hewengao 20160719 start*/
	             LogManager.w(Constant.TAG, "update: ", e);
	             /*SDK-550 hewengao 20160719 end*/
			}
			return rows;
	    }
		
		 /**
		  * 是否有记录
		  * @param tableName
		  * @param feildName
		  * @param where
		  * @param args
		  * @return
		  */
		 public static boolean hasRecord(String tableName,String feildName,String where,String... args){
				XyCursor cur = null;
				try {
					cur =DBManager.query(tableName,
							new String[]{feildName},
							where ,args);
					if(cur != null&&cur.getCount()>0){
						return true;
					}
				} catch (Throwable e) {
//					e.printStackTrace();
				    /*SDK-550 hewengao 20160719 start*/
		             LogManager.w(Constant.TAG, "hasRecord: ", e);
		             /*SDK-550 hewengao 20160719 end*/
				}finally{
					XyCursor.closeCursor(cur, true);
				}
			 return false;
		 }
}
